package com.bwie.test;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.domain.Student;
import com.bwie.es.EsStudent;
import com.bwie.mapper.StuMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: lrz
 * @Date: 2024/11/4 09:06
 * @Description:
 **/
@Component
@Slf4j
public class SysStudent implements Job {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    StuMapper stuMapper;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        System.out.println("同步数据开始");

        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(EsStudent.class);
        if(!indexOperations.exists()){
            indexOperations.create();

            Document mapping = indexOperations.createMapping();
            indexOperations.putMapping(mapping);
        }

        List<Student> students = stuMapper.selectList(null);

        for (Student student : students) {
            EsStudent esStudent = BeanUtil.toBean(student, EsStudent.class);

            elasticsearchRestTemplate.save(esStudent);
        }

        System.out.println("同步数据结束");

    }
}
